//
//  KLineWrapper.swift
//  Trans
//
//  Created by zcj on 2024/12/11.
//

import SwiftUI

struct KLineWrapper: NSViewRepresentable {
    @ObservedObject var points: PointArr
    
       func makeNSView(context: Context) -> KLineView {
           let view = KLineView()
           view.points = points
           return view
       }
    
       func updateNSView(_ nsView: KLineView, context: Context) {
           print("upate klineview")
           nsView.points = points
           nsView.setNeedsDisplay(nsView.frame)
       }
}


struct KLineViewCtl : View{
    @State var pointArr: PointArr = PointArr()
    @State var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    @Binding var absolutePath:String
    var body: some View {
        VStack{
            Text("pointArr.lastSpeed is  : \(size2StrFormat(dnum: pointArr.lastSpeed))")
            Divider().background(kcolors.lineColor)
                .padding(.horizontal,0)
            KLineWrapper(points: pointArr)
                .onAppear(){
                    timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
                }
                .onDisappear(){
                    self.timer.upstream.connect().cancel()
                }
                .onReceive(timer){time in
                    self.updatePointArrWithTime()
                }
        }.border(.gray,width: 1)
            .clipShape(RoundedRectangle(cornerRadius: 5,style: .continuous))
    }
    
    func updatePointArrWithTime(){
        if absolutePath.isEmpty{
            return
        }
        fileDownloadArr.array.forEach { ftm in
            if ftm.absolutePath == absolutePath,ftm.state == DOWNLOADING{
                if ftm.downloadSize == ftm.totalSize {
                    return
                }
                let prePoint = pointArr.lastPoint
              
                pointArr.lastPoint = CGPoint(x: Date().timeIntervalSince1970, y: CGFloat(ftm.downloadSize))
             
                if pointArr.lastPoint.y > pointArr.high.y {
                    pointArr.high = pointArr.lastPoint
                }else if pointArr.lastPoint.y < pointArr.low.y{
                    pointArr.low = pointArr.lastPoint
                }
                pointArr.arr.append(pointArr.lastPoint)
                //更新最大和最小速度
                let newSpeed = (pointArr.lastPoint.y - prePoint.y )/(pointArr.lastPoint.x - prePoint.x)
                
                pointArr.lastSpeed = newSpeed
                if (newSpeed > pointArr.maxSpeed){
                    pointArr.maxSpeed = newSpeed
                }else if (newSpeed < pointArr.minSpeed){
                    pointArr.minSpeed = newSpeed
                }
            }
        }
    }
    
    
}
